<template>
  <div class="import--wrap">
    <div class="table--head">
      <div :style="{ color: '#000', fontSize: '28px', fontWeight: '500' }">
        查看数据
      </div>
      <!-- <div>
        <span :style="{ marginRight: '15px' }">日期选择:</span>
        <a-range-picker v-model:value="dateVal" show-time />
      </div> -->
      <div>
        <a-radio-group v-model:value="type" @change="sexChange">
          <a-radio-button value="ALL">所有</a-radio-button>
          <a-radio-button value="男">男</a-radio-button>
          <a-radio-button value="女">女</a-radio-button>
        </a-radio-group>
      </div>
    </div>
    <div class="table--con">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :row-selection="rowSelection"
        :row-key="(record) => record.sno"
        :pagination="false"
        :scroll="{ x: 1500, y: 650 }"
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex === 'sex'">
            <a-tag :color="text === '男' ? 'geekblue' : 'volcano'">{{
              text
            }}</a-tag>
          </template>
          <template v-if="column.dataIndex === 'action'">
            <span class="down--btn" @click="downData(record)">下载</span>
            <span class="down--btn" @click="getPdf(record)">查看报告</span>
            <span class="down--btn" @click="getImgsByName(record)"
              >查看图片</span
            >
            <span class="down--btn" @click="getForce(record)">查看接触力</span>
            <span class="down--btn" @click="getPose(record)">查看位姿</span>
          </template>
        </template>
      </a-table>
    </div>
    <div class="pagination--box">
      <a-config-provider>
        <a-pagination
          show-quick-jumper
          v-model="current"
          :page-size-options="pageSizeOptions"
          :total="total"
          show-size-changer
          :page-size="pageSize"
          @showSizeChange="onShowSizeChange"
          @change="handleTableChange"
        >
        </a-pagination>
      </a-config-provider>
    </div>
    <ModalSlot
      title="查看报告"
      :open="pdfKey"
      @on-handleOk="pdfKey = false"
      :width="1280"
    >
      <div class="pdf--box">
        <embed
          :src="item"
          width="100%"
          height="100%"
          type="application/pdf"
          v-for="item in pdfUrls"
          :key="item"
        />
      </div>
    </ModalSlot>
    <ModalSlot
      title="查看图片"
      :open="imgKey"
      @on-handleOk="imgKey = false"
      :width="1280"
    >
      <div class="pdf--box">
        <img :src="item" alt="" v-for="item in imgs" :key="item" />
      </div>
    </ModalSlot>
    <ModalSlot
      title="接触力"
      :open="forceKey"
      @on-handleOk="forceKey = false"
      :width="1280"
    >
      <div class="pdf--box"><MyEcharts ref="force" /><</div>
    </ModalSlot>
    <ModalSlot
      title="机器人位姿"
      :open="poseKey"
      @on-handleOk="poseKey = false"
      :width="1280"
    >
      <div class="pdf--box"><MyEcharts ref="pose" /><</div>
    </ModalSlot>
  </div>
</template>

<script>
import { UploadOutlined } from "@ant-design/icons-vue";
import { tableColumns } from "@/utils";
import {
  getChineseMedicineByPage,
  getPdfByName,
  getImgsByName,
  getForceByName,
  getPoseByName,
} from "@/api";
import * as XLSX from "xlsx";
import moment from "moment";
import ModalSlot from "@/components/MySlot.vue";
import MyEcharts from "../components/MyEcharts.vue";
export default {
  name: "ViewData",
  data() {
    return {
      dateVal: null,
      type: "ALL",
      tableData: [],
      columns: tableColumns,
      total: 0,
      current: 1,
      pageSize: 10,
      pageSizeOptions: ["10", "20", "30"],
      selectedRowKeys: [],
      selectOpt: [
        { name: "name", value: "name" },
        { name: "sex", value: "sex" },
        { name: "pos", value: "pos" },
        { name: "age", value: "age" },
        { name: "department", value: "department" },
        { name: "seen", value: "seen" },
        { name: "tips", value: "tips" },
      ],
      selectVal: ["name", "sex", "tips", "department"],
      pdfKey: false,
      pdfUrls: null,
      imgKey: false,
      imgs: null,
      forceKey: false,
      forceData: null,
      poseKey: false,
      poseData: null,
    };
  },
  computed: {
    rowSelection() {
      return {
        type: "radio",
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      };
    },
  },
  components: {
    UploadOutlined,
    ModalSlot,
    MyEcharts,
  },
  mounted() {
    this.getChineseMedicineByPage();
  },
  methods: {
    async getChineseMedicineByPage() {
      let params = {
        page: this.current,
        limit: this.pageSize,
      };
      if (this.type != "ALL") {
        const where = {
          sex: this.type,
        };
        params.where = where;
      }
      const res = await getChineseMedicineByPage(
        window.CONFIG.server_url,
        params
      );
      if (res.code == 200) {
        this.total = res.data.count;
        this.tableData = res.data.rows;
      }
      console.log(res);
    },
    onShowSizeChange(current, pageSize) {
      this.pageSize = pageSize;
    },
    handleTableChange(pagination) {
      this.current = pagination;
      this.getChineseMedicineByPage();
      if (this.selectRecord) {
        this.selectedRowKeys = [];
      }
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    sexChange() {
      this.getChineseMedicineByPage();
    },
    downData(val) {
      if (!this.selectedRowKeys.length || !val) {
        this.$message.error("请选择数据!");
        return;
      }
      const selectedRecords =
        this.tableData.filter((item) =>
          this.selectedRowKeys.includes(item.sno)
        ) || val;
      if (selectedRecords.length === 0 || !selectedRecords) {
        this.$message.error("未找到选中的数据!");
        return;
      }
      const headers = {
        sno: "编号",
        name: "姓名",
        sex: "性别",
        age: "年龄",
        department: "科室",
        pos: "部位",
        diagnosis_chinese: "中医诊断",
        diagnosis_western: "西医诊断",
        seen: "症状",
        tips: "医嘱",
      };
      // 转换数据（使用中文表头）
      const dataForExport = selectedRecords.map((record) => {
        const newRecord = {};
        Object.keys(headers).forEach((key) => {
          newRecord[headers[key]] = record[key];
        });
        return newRecord;
      });

      // 创建工作表
      const ws = XLSX.utils.json_to_sheet(dataForExport);

      // 创建工作簿
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, "中药数据");

      // 生成Excel文件并下载
      const fileName = `中药数据_${moment().format(
        "YYYY-MM-DD HH:mm:ss"
      )}.xlsx`;
      XLSX.writeFile(wb, fileName);
    },
    async getPdf(val) {
      // console.log("getPdf val", val);
      // return;
      const res = await getPdfByName(window.CONFIG.server_url, {
        name: val.name,
      });
      if (res.code == 200) {
        this.pdfKey = true;
        this.pdfUrls = res.data;
      } else {
        this.$message.error("获取pdf出错");
      }
    },
    async getImgsByName(val) {
      // console.log("getImgsByName val", val);
      // return;
      const res = await getImgsByName(window.CONFIG.server_url, {
        name: val.name,
      });
      if (res.code == 200) {
        this.imgKey = true;
        this.imgs = res.data;
      } else {
        this.$message.error("获取图片出错");
      }
    },
    async getForce(val) {
      // console.log("getForce val", val);
      //  return;
      const res = await getForceByName(window.CONFIG.server_url, {
        name: val.name,
      });
      if (res.code == 200) {
        this.forceKey = true;
        this.forceData = res.data;
        this.$nextTick(() => {
          this.initForeEcharts(this.forceData);
        });
      } else {
        this.$message.error("获取接触力出错");
      }
    },
    initForeEcharts(data) {
      const option = {
        xAxis: {
          type: "category",
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data,
            type: "line",
            smooth: true,
          },
        ],
      };
      this.$refs.force.drawChart(option);
    },
    async getPose(val) {
      // console.log("getPose val", val);
      //  return;
      const res = await getPoseByName(window.CONFIG.server_url, {
        name: val.name,
      });
      if (res.code == 200) {
        this.poseKey = true;
        this.poseData = res.data;
        this.$nextTick(() => {
          this.initPoseEcharts(this.forceData);
        });
      } else {
        this.$message.error("获取机器人位姿出错");
      }
    },
    initPoseEcharts(data) {
      const option = {
        xAxis: {
          type: "category",
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data,
            type: "line",
            smooth: true,
          },
        ],
      };
      this.$refs.pose.drawChart(option);
    },
  },
};
</script>

<style scoped lang="less">
@import "@/assets/import.less";
</style>
